package com.shaoshaohuo.app.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by Administrator on 2017/8/18.
 */

public class BitmapUtils {
    /**
     *
     */
    public static File zipbit(String pathfile, Context context){
        File file = new File(pathfile);
        File file2 = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "mmag");
        if(!file2.exists()){
            file2.mkdirs();
        }
//        if(){}
        if(file.exists()){
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds=true;
            BitmapFactory.decodeFile(file.getAbsolutePath(),options);
            int outHeight = options.outHeight;
            int outWidth = options.outWidth;
            float simeple=1;
            //我们去屏幕的8/1
            float hh = context.getResources().getDisplayMetrics().heightPixels;//这里设置高度为800f
            float ww = context.getResources().getDisplayMetrics().widthPixels;//这里设置宽度为480f
            while(outHeight/simeple>hh||outWidth/simeple>ww){
                simeple*=2;
            }
            options.inJustDecodeBounds=false;
            options.inSampleSize= (int) simeple;
            Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);

            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG,100,byteArrayOutputStream);
            Log.e("TAG", "zipbit: "+byteArrayOutputStream.toByteArray().length/(1024f*1024f) );
              int len=100;
              while (byteArrayOutputStream.toByteArray().length/(1024*1024)>1024*1024*1){
                  len-=5;
                  if(len<=0){
                      break;
                  }
                  bitmap.compress(Bitmap.CompressFormat.JPEG,len,byteArrayOutputStream);
              }
            byte[] bytes = byteArrayOutputStream.toByteArray();
            long l = System.currentTimeMillis();
            File file1 = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator+ "mmag" + File.separator, l + ".jpg");

            try {
                FileOutputStream fileOutputStream = new FileOutputStream(file1);
                fileOutputStream.write(bytes);
                fileOutputStream.flush();
                fileOutputStream.close();
                return file1;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }



}
